package fileutils

import (
	"fmt"
	"gitee.com/ichub/webcli/common/base/baseconsts"
	"github.com/sirupsen/logrus"
	"os"
	"path"
	"runtime"
	"strings"
)

const DEFINE_YML_PATHFILE = "/config/ichubengine.yml"

func CheckConfigFileExist(winroot string) bool {
	return CheckFileExist(winroot + DEFINE_YML_PATHFILE)
}

func FindRootDir() string {

	if runtime.GOOS == "linux" {
		var rootdir = os.Getenv(baseconsts.IchubBasePath)
		if len(rootdir) == 0 {
			var rootdir, _ = os.Getwd()
			os.Setenv(baseconsts.IchubBasePath, rootdir)
			return rootdir
		}
	} else {

		var windir = FindRootDirWin()
		os.Setenv(baseconsts.IchubBasePath, windir)
		return windir
	}
	return ""
}

func GetCurPath() string {
	var paths string
	paths, _ = os.Getwd()
	return paths
}

func FindRootDirWin() string {

	var wr = GetCurPath() //r, _ := os.Getwd()
	var dirs = strings.Split(wr, "\\")
	if len(dirs) < 2 {
		dirs = strings.Split(wr, "/")
	}

	var workRoot = strings.Join(dirs, "\\")
	var i = len(dirs)
	for i > 0 {
		i--
		if CheckConfigFileExist(workRoot) {
			os.Setenv(baseconsts.IchubBasePath, workRoot)
			return workRoot
		}
		workRoot = strings.Join(dirs[0:i], "\\")
	}

	return workRoot
}

func GetHomePath() string {
	var paths string
	_, filename, _, ok := runtime.Caller(0)
	if ok {
		paths = path.Dir(filename)
	}
	logrus.Info(paths)
	return paths
}
func CheckFileExist(filename string) bool {
	_, err := os.Stat(filename)
	if os.IsNotExist(err) {
		return false
	}

	fmt.Errorf("file exists !%s\r\n", filename)
	return true

}
